import React from 'react';
import { connect } from 'react-redux'
import { BrowserRouter as Router, Route, Switch, Redirect } from 'react-router-dom'
import { setUserInfo } from '@/redux/action'
import { storage } from '@/utils'
import { BASENAME } from '@/config'

import App from '../App'

import Login from '@/pages/login/Login'

import renderRoutes from './renderRoutes';
import { baseRouter } from './routes';

const basename = BASENAME    // 路由器的默认根路径，如果你的页面部署在服务器的二级（子）目录，你需要将 basename 设置到此子目录。
const indexPath = '/home' // 默认页面
const authPath = '/login' // 默认未登录的时候返回的页面

class MyRouter extends React.Component {
  constructor(props) {
    super(props)
    let userInfo = storage.localStorage.get('userInfo')

    // 写入store
    let { dispatch } = props
    dispatch(setUserInfo(userInfo));
    this.isLogin = userInfo ? true : false
  }

  render () {
    let isLogin = true
    // let userInfo = storage.localStorage.get('userInfo')

    // if (this.isLogin || userInfo) {
      // isLogin = true
    // }
    console.log("isLogin-----------", isLogin)

    return (
      <Router basename={basename} >
        <Switch>
          <Route exact path={['/', '/login']} render={(props) => {
            if (isLogin) {
              // 如果已经登录，重定向到默认页
              return <Redirect to={indexPath} />
            } else {
              return <Login {...props} />
            }
          }} />
          <App>
            {renderRoutes(baseRouter, isLogin, authPath, indexPath)}
          </App>
        </Switch>
      </Router>
    )
  }
}

const mapStateToProps = state => {
  return {
    userInfo: state.userInfo,
  }
};
export default connect(mapStateToProps)(MyRouter)
